import { ref, computed, onUnmounted } from 'vue'

/**
 * 性能指标接口
 */
interface PerformanceMetric {
  name: string
  startTime: number
  endTime?: number
  duration?: number
  metadata?: Record<string, any>
}

/**
 * 性能统计接口
 */
interface PerformanceStats {
  totalOperations: number
  averageDuration: number
  minDuration: number
  maxDuration: number
  lastDuration: number
}

/**
 * 性能监控组合式函数
 */
export function usePerformanceMonitor() {
  // 当前活跃的性能跟踪
  const activeTracking = ref<Map<string, PerformanceMetric>>(new Map())
  
  // 已完成的性能指标
  const completedMetrics = ref<PerformanceMetric[]>([])
  
  // 性能统计缓存
  const statsCache = ref<Map<string, PerformanceStats>>(new Map())
  
  // 是否启用性能监控
  const isEnabled = ref(process.env.NODE_ENV === 'development')
  
  /**
   * 开始跟踪性能
   */
  function startTracking(name: string, metadata?: Record<string, any>): void {
    if (!isEnabled.value) return
    
    const metric: PerformanceMetric = {
      name,
      startTime: performance.now(),
      metadata
    }
    
    activeTracking.value.set(name, metric)
  }
  
  /**
   * 停止跟踪性能
   */
  function stopTracking(name: string): number | null {
    if (!isEnabled.value) return null
    
    const metric = activeTracking.value.get(name)
    if (!metric) {
      console.warn(`Performance tracking not found: ${name}`)
      return null
    }
    
    const endTime = performance.now()
    const duration = endTime - metric.startTime
    
    const completedMetric: PerformanceMetric = {
      ...metric,
      endTime,
      duration
    }
    
    // 移除活跃跟踪
    activeTracking.value.delete(name)
    
    // 添加到已完成指标
    completedMetrics.value.push(completedMetric)
    
    // 更新统计缓存
    updateStats(name, duration)
    
    // 限制已完成指标数量（保留最近1000条）
    if (completedMetrics.value.length > 1000) {
      completedMetrics.value = completedMetrics.value.slice(-1000)
    }
    
    return duration
  }
  
  /**
   * 测量函数执行时间
   */
  function measure<T>(name: string, fn: () => T, metadata?: Record<string, any>): T {
    if (!isEnabled.value) return fn()
    
    startTracking(name, metadata)
    try {
      const result = fn()
      return result
    } finally {
      stopTracking(name)
    }
  }
  
  /**
   * 测量异步函数执行时间
   */
  async function measureAsync<T>(
    name: string, 
    fn: () => Promise<T>, 
    metadata?: Record<string, any>
  ): Promise<T> {
    if (!isEnabled.value) return fn()
    
    startTracking(name, metadata)
    try {
      const result = await fn()
      return result
    } finally {
      stopTracking(name)
    }
  }
  
  /**
   * 更新性能统计
   */
  function updateStats(name: string, duration: number): void {
    const existing = statsCache.value.get(name)
    
    if (!existing) {
      statsCache.value.set(name, {
        totalOperations: 1,
        averageDuration: duration,
        minDuration: duration,
        maxDuration: duration,
        lastDuration: duration
      })
    } else {
      const newTotal = existing.totalOperations + 1
      const newAverage = (existing.averageDuration * existing.totalOperations + duration) / newTotal
      
      statsCache.value.set(name, {
        totalOperations: newTotal,
        averageDuration: newAverage,
        minDuration: Math.min(existing.minDuration, duration),
        maxDuration: Math.max(existing.maxDuration, duration),
        lastDuration: duration
      })
    }
  }
  
  /**
   * 获取性能统计
   */
  function getStats(name?: string): PerformanceStats | Map<string, PerformanceStats> {
    if (name) {
      return statsCache.value.get(name) || {
        totalOperations: 0,
        averageDuration: 0,
        minDuration: 0,
        maxDuration: 0,
        lastDuration: 0
      }
    }
    return new Map(statsCache.value)
  }
  
  /**
   * 获取最近的性能指标
   */
  function getRecentMetrics(count = 10): PerformanceMetric[] {
    return completedMetrics.value.slice(-count)
  }
  
  /**
   * 按名称过滤性能指标
   */
  function getMetricsByName(name: string): PerformanceMetric[] {
    return completedMetrics.value.filter(metric => metric.name === name)
  }
  
  /**
   * 清除所有性能数据
   */
  function clear(): void {
    activeTracking.value.clear()
    completedMetrics.value = []
    statsCache.value.clear()
  }
  
  /**
   * 清除指定名称的性能数据
   */
  function clearByName(name: string): void {
    activeTracking.value.delete(name)
    completedMetrics.value = completedMetrics.value.filter(metric => metric.name !== name)
    statsCache.value.delete(name)
  }
  
  /**
   * 导出性能报告
   */
  function exportReport(): {
    activeTracking: PerformanceMetric[]
    completedMetrics: PerformanceMetric[]
    stats: Record<string, PerformanceStats>
    timestamp: number
  } {
    return {
      activeTracking: Array.from(activeTracking.value.values()),
      completedMetrics: completedMetrics.value,
      stats: Object.fromEntries(statsCache.value),
      timestamp: Date.now()
    }
  }
  
  /**
   * 计算属性：活跃跟踪数量
   */
  const activeTrackingCount = computed(() => activeTracking.value.size)
  
  /**
   * 计算属性：已完成指标数量
   */
  const completedMetricsCount = computed(() => completedMetrics.value.length)
  
  /**
   * 计算属性：性能概览
   */
  const performanceOverview = computed(() => {
    const stats = Array.from(statsCache.value.entries())
    const totalOperations = stats.reduce((sum, [, stat]) => sum + stat.totalOperations, 0)
    const averageOfAverages = stats.length > 0 
      ? stats.reduce((sum, [, stat]) => sum + stat.averageDuration, 0) / stats.length 
      : 0
    
    return {
      totalOperations,
      averageOfAverages,
      uniqueOperations: stats.length,
      activeTracking: activeTrackingCount.value
    }
  })
  
  // 组件卸载时清理
  onUnmounted(() => {
    // 停止所有活跃跟踪
    for (const name of activeTracking.value.keys()) {
      stopTracking(name)
    }
  })
  
  return {
    // 状态
    isEnabled,
    activeTrackingCount,
    completedMetricsCount,
    performanceOverview,
    
    // 方法
    startTracking,
    stopTracking,
    measure,
    measureAsync,
    getStats,
    getRecentMetrics,
    getMetricsByName,
    clear,
    clearByName,
    exportReport
  }
}
